//
//  YKHomeViewController.m
//  youkan
//
//  Created by mac mini on 16/2/24.
//  Copyright © 2016年 Honsintech. All rights reserved.
//

#import "YKHomeViewController.h"

#import "UIBarButtonItem+Item.h"
#import "YKTitleButton.h"
#import "MJRefresh.h"
#import "YKAccountTool.h"
//#import "AFNetworking.h"
#import "UIImageView+WebCache.h"
#import "YKHttpTool.h"
#import "YKUserTool.h"

#import "YKStatuesTool.h"
#import "YKWBStatues.h"
#import "YKAccount.h"
#import "YKPopMenu.h"
#import "YKCover.h"
#import "YKOneViewController.h"

#import "YKUser.h"
#import "MJExtension.h"

#import "YKStatusCell.h"
#import "YKStatusFrame.h"
@interface YKHomeViewController ()<YKCoverDelegate>
@property(nonatomic,weak)YKTitleButton *titleButton;

@property(nonatomic,strong)YKOneViewController *one;

//@property(nonatomic,strong)NSMutableArray *statuses;
/*viewModel  :YKStatusFrame */
@property(nonatomic,strong)NSMutableArray *statusFrame;

@end

@implementation YKHomeViewController
//-(NSMutableArray *)statuses{
//    if (!_statuses) {
//        _statuses =[NSMutableArray array];
//    }
//    return _statuses;
//}
-(NSMutableArray *)statusFrame{
    if (!_statusFrame) {
        _statusFrame =[NSMutableArray array];
    }
    return _statusFrame;
}
-(YKOneViewController *)one{
    if (!_one) {
        _one =[[YKOneViewController alloc]init];
    }
    return _one;
}
// UIBarButtonItem:决定导航条上按钮的内容
// UINavigationItem:决定导航条上内容
// UITabBarItem:决定tabBar上按钮的内容
// ios7之后，会把tabBar上和导航条上的按钮渲染
// 导航条上自定义按钮的位置是由系统决定，尺寸才需要自己设置。
- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpNavgationBar];

    if ([self respondsToSelector:@selector(automaticallyAdjustsScrollViewInsets)]) {
        self.automaticallyAdjustsScrollViewInsets = NO ;
    }
    
//    self.navigationController.navigationBar.translucent = NO;
//    self.tableView.contentInset = UIEdgeInsetsMake(44, 0, 0, 0);
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor =[UIColor lightGrayColor];

    [self.tableView setMj_header:[MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadNewStatus)]];
    [self.tableView.mj_header beginRefreshing];
    [self.tableView setMj_footer:[MJRefreshBackStateFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreStatus)]];
//    [self.tableView addHeaderWithTarget:self action:@selector(loadNewStatus)];
//    [self.tableView.mj_header setRefreshingTarget:self refreshingAction:@selector(loadNewStatus)];
//    [self.tableView headerBeginRefreshing];
//    [self.tableView addFooterWithTarget:self action:@selector(loadMoreStatus)];
 
    if (@available(iOS 11.0 , *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        self.tableView.contentInset = UIEdgeInsetsMake(kStatusBarHeight+KNavigationBarHeight, 0, kTabbarHeight+kHomeIndicatorHeight, 0);
        self.tableView.scrollIndicatorInsets = self.tableView.contentInset;
    }
//      请求当前用户的昵称(判断与之前昵称)
    [YKUserTool userInfoWithSucces:^(YKUser *user) {
//      请求到当前用户的信息 设置导航栏的标题
        [self.titleButton setTitle:user.name forState:UIControlStateNormal];
//      获取当前的账号
        YKAccount *account =[YKAccountTool account];
        account.name = user.name;
        [YKAccountTool saveAccount:account];
    } failure:^(NSError *error) {

    }];
}
#pragma mark -刷新最新的微博数(下拉)
-(void)refresh{
//    自动下拉刷新
    [self.tableView.mj_header beginRefreshing];

}
#pragma mark - 请求以前的微博数据(上拉)
-(void)loadMoreStatus{
    NSString *maxId=nil;
    if (self.statusFrame.count) {
        YKStatusFrame *statusF = self.statusFrame.lastObject ;
//        YKWBStatues *sta =[[self.statusFrame lastObject] status];
        maxId = statusF.status.idstr ;
    }
  //  数据层： 将网络层中的数据进行格式化，并返回到数据层
    [YKStatuesTool moreStatusWithMaxId:maxId success:^(NSArray *statuses) {
        [self.tableView.mj_footer endRefreshing];
        NSMutableArray *statFramArr=[NSMutableArray array];
        for (YKWBStatues *status in statuses) {
            YKStatusFrame *statusF =[[YKStatusFrame alloc]init];
            statusF.status =status;
            [statFramArr addObject:statusF];
        }
        [self.statusFrame addObjectsFromArray:statFramArr];
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        YKLog(@"loadMoreStatuserrror%@",error);
    }];

/*
//    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    YKAccount *account =[YKAccountTool account];
//    if (self.statuses.count) {//有微博数据才需要刷新
//               params[@"max_id"]=[[self.statuses lastObject] idstr];
////        params[@"since_id"]=[self.statuses[0] idstr];
//    }
//    params[@"access_token"]=account.access_token;
//    //    access_token	true	string	采用OAuth授权方式为必填参
//    [manager GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        //        YKLog(@"responseObject==%@",responseObject);
//        // 数据转模型  1.获取微博字典数组
//        [self.tableView footerEndRefreshing];
//        NSArray *dictArr =responseObject[@"statuses"];
//        NSArray *statuses = (NSMutableArray*)[YKStatues objectArrayWithKeyValuesArray:dictArr];
//        NSIndexSet *indexSet =[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
//        [self.statuses insertObjects:statuses atIndexes:indexSet];
//        [self.tableView reloadData];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        //        YKLog(@"error==%@",error);
//    }];
    */
}
#pragma mark -展示最新的微博数
-(void)showNewStatusCount:(NSInteger)count{
    if (count ==0) return;
    CGFloat h =35;
    CGFloat y = CGRectGetMaxY(self.navigationController.navigationBar.frame)-h;
    CGFloat w = self.view.width;
    UILabel *titleL =[[UILabel alloc]initWithFrame:CGRectMake(0, y, w, h)];
//    通过图片获取到颜色值 [UIColor colorWithPatternImage: ]
    titleL.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"timeline_new_status_background"]];
    titleL.text =[NSString stringWithFormat:@"最新微博数%ld",count];
    titleL.textColor =[UIColor whiteColor];
    titleL.textAlignment =NSTextAlignmentCenter;
///      插入到导航条下面，导航控制器下有个view，这个view里有个navigationBar
    [self.navigationController.view insertSubview:titleL belowSubview:self.navigationController.navigationBar];
//    新增的提示动画出现
    [UIView animateWithDuration:0.25 animations:^{
        //      动画平移
        titleL.transform =CGAffineTransformMakeTranslation(0, h);
    } completion:^(BOOL finished) {
//        动画出现后，隔2s执行向上的消失动画
        [UIView animateWithDuration:0.25 delay:2 options:UIViewAnimationOptionCurveLinear animations:^{
            titleL.transform =CGAffineTransformIdentity;
        } completion:^(BOOL finished) {
//            向上消失后移除titleL
            [titleL removeFromSuperview];
        }];
    }];
}
#pragma mark -请求最新的微博
-(void)loadNewStatus{
    NSString *sinceId=nil;
    if (self.statusFrame.count) {
        YKStatusFrame *statusF =self.statusFrame.firstObject;
        sinceId = statusF.status.idstr ;
    }
        [YKStatuesTool newStatusWithSinceId:sinceId success:^(NSArray *statuses) {
//        展示最新的微博数
        [self showNewStatusCount:statuses.count];
        NSIndexSet *indexSet =[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
//        [self.tableView headerEndRefreshing];
        [self.tableView.mj_header endRefreshing];
//        普通模型转视图模型 YKStatues=>YKStatusFrame
        NSMutableArray *statusFrameArr =[NSMutableArray array];
        for (YKWBStatues  *status in statuses) {
            YKStatusFrame *statusF =[[YKStatusFrame alloc]init];
            statusF.status=status;
            [statusFrameArr addObject:statusF];
        }
        [self.statusFrame insertObjects:statusFrameArr atIndexes:indexSet];
//        YKLog(@"self.statusFrame===%@",self.statusFrame);
        [self.tableView reloadData];
    } failure:^(NSError *error) {
        YKLog(@"loadNewStatuserrror=%@",error);
//        [self.tableView headerEndRefreshing];
        [self.tableView.mj_header endRefreshing];
    }];

/*
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    YKAccount *account =[YKAccountTool account];
//        if (self.statuses.count) {
//            long long maxId = [[[self.statuses lastObject] idstr ] longLongValue];
//            params[@"since_id"]=[NSString stringWithFormat:@"%lld",maxId-1];
//        }
//    params[@"access_token"]=account.access_token;
//
//    [YKHttpTool GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(id responseObject) {
//        [self.tableView headerEndRefreshing];
//        NSArray *dictArr =responseObject[@"statuses"];
//       NSArray *statuses = (NSMutableArray*)[YKStatues objectArrayWithKeyValuesArray:dictArr];
//        NSIndexSet *indexSet =[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
//        [self.statuses insertObjects:statuses atIndexes:indexSet];
//        [self.tableView reloadData];
//
//           } failure:^(NSError *error) {
//
//    }];
*/
/*
//    AFHTTPRequestOperationManager *manager =[AFHTTPRequestOperationManager manager];
//    NSMutableDictionary *params = [NSMutableDictionary dictionary];
//    YKAccount *account =[YKAccountTool account];
//    if (self.statuses.count) {
//        long long maxId = [[[self.statuses lastObject] idstr ] longLongValue];
//        params[@"since_id"]=[NSString stringWithFormat:@"%lld",maxId-1];
//    }
//    params[@"access_token"]=account.access_token;
////    access_token	true	string	采用OAuth授权方式为必填参
//    [manager GET:@"https://api.weibo.com/2/statuses/friends_timeline.json" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
////        YKLog(@"responseObject==%@",responseObject);
//        // 数据转模型  1.获取微博字典数组
//        [self.tableView headerEndRefreshing];
//        NSArray *dictArr =responseObject[@"statuses"];
//       NSArray *statuses = (NSMutableArray*)[YKStatues objectArrayWithKeyValuesArray:dictArr];
//        NSIndexSet *indexSet =[NSIndexSet indexSetWithIndexesInRange:NSMakeRange(0, statuses.count)];
//        [self.statuses insertObjects:statuses atIndexes:indexSet];
//        [self.tableView reloadData];
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
////        YKLog(@"error==%@",error);
//    }];
 */

}
#pragma mark -设置导航条
-(void)setUpNavgationBar{
    self.navigationItem.leftBarButtonItem =[UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_friendsearch"] highImage:[UIImage imageNamed:@"navigationbar_friendsearch_highlighted"] target:self action:@selector(friendsearch) forControlEvents:UIControlEventTouchUpInside];

    self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithImage:[UIImage imageNamed:@"navigationbar_pop"] highImage:[UIImage imageNamed:@"navigationbar_pop_highlighted"] target:self action:@selector(pop) forControlEvents:UIControlEventTouchUpInside];

    YKTitleButton *titleButton  =[YKTitleButton buttonWithType: UIButtonTypeCustom];
    _titleButton =titleButton;
    NSString *title =[YKAccountTool account].name?:@"首页";
    [titleButton setTitle:title forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_up"] forState:UIControlStateNormal];
    [titleButton setImage:[UIImage imageNamed:@"navigationbar_arrow_down"] forState:UIControlStateSelected];
    [titleButton addTarget:self action:@selector(titleClick:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.titleView =titleButton;
    // 高亮的时候不需要调整图片
    titleButton.adjustsImageWhenHighlighted =NO;

}
-(void)titleClick:(UIButton*)button{
    button.selected = !button.selected;
    YKLog(@"%@",button.currentImage);
    YKCover *cover =[YKCover show];
    cover.delegate = self;

    CGFloat popW= 200;
    CGFloat popX= (self.view.width-200)*0.5;
    CGFloat popH = popW;
    CGFloat popY = 55;
    YKPopMenu *menu = [YKPopMenu showInRect:CGRectMake(popX, popY, popW, popH)];
    menu.contentView = self.one.view;
}
#pragma mark -YKCoverDelegate方法
-(void)coverDidClickCover:(YKCover *)cover{
    [YKPopMenu hide];
    _titleButton.selected = NO;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}
-(void)friendsearch{
//    YKLog(@"%s",__func__);
}
-(void)pop{
//        [_titleButton setTitle:@"首页首页" forState:UIControlStateNormal];
//    [_titleButton setImage:nil forState:UIControlStateNormal];
    //    [_titleButton sizeToFit];
}



#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.statusFrame.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    YKStatusFrame *statusF =self.statusFrame[indexPath.row];
    return statusF.cellHeight;

}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    YKStatusCell *cell =[YKStatusCell cellWithTalbeView:tableView];
//      获取对应的模型
    YKStatusFrame *statusF = self.statusFrame[indexPath.row];
    cell.statusF =statusF;
    return cell;
}


/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
